package net.scdx.hotel.service.impl;

import net.scdx.hotel.dto.UserExecution;
import net.scdx.hotel.entity.User;
import net.scdx.hotel.mapper.UserMapper;
import net.scdx.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserExecution addUser(User user) throws Exception {
        boolean success = true;
        String msg = "";

        if (user.getUsername()== null || user.getUsername() == null || user.getUsername().trim() == "" || user.getPassword().trim() == "") {
            msg = "username or password is empty";
            success = false;
        }
        else{

        if (userMapper.queryUserByUsernameOrPsw(user.getUsername(),null) != null)
            return new UserExecution(false, "duplicate username", null);

        int effectedNum = userMapper.insert(user);
        if (effectedNum <= 0){
            success = false;
            msg = "insert into database failure";
        }
    }

        return new UserExecution(success, msg,null);
    }

    @Override
    public UserExecution userLogin(String username, String password) throws Exception {
        boolean success = true;
        String msg = "";

        if (username == null || password == null || username.trim() == "" || password.trim() == "")
            return new UserExecution(false, "username or password is empty", null);

        // query user
        User user = userMapper.queryUserByUsernameOrPsw(username, password);
        if (user == null) {
            success = false;
            msg = "username or password is wrong";
        }

        return new UserExecution(success, msg, user);
    }

    @Override
    public User userInfo(String username) throws Exception{
        User user = userMapper.queryUserByUsernameOrPsw(username, null);
        return user;
    }

    @Override
    public boolean midifyUser(User user) throws Exception {
        int effectedNum = userMapper.update(user);
        if (effectedNum > 0)
            return true;
        return false;
    }

    @Override
    public List<User> usersInfo(Integer adminId) throws Exception{
        List<User>  users= userMapper.selectByForeignKey(adminId);
        return users;
    }

    @Override
    public void deleteUserById(Integer userId) throws Exception{
        userMapper.deleteUser(userId);
    }

    @Override
    public User findUserById(Integer userId) throws Exception {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public void saveUser(User user) throws Exception{
        if(user.getUserId() == null || user.getUserId().equals("")) {
            userMapper.insert(user);
        } else {
            userMapper.updateByPrimaryKey(user);
        }
    }
}
